from machine import PWM,Pin
import socket
import time
import network


#连接热点
def do_connect():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('meik30s', '5201314ygyu')  #配置热点名称和密码
        i = 1
        while not wlan.isconnected():
            print("正在链接...{}".format(i))
            i += 1
            time.sleep(1)
    print('network config:', wlan.ifconfig())
    
do_connect()

#配置UDP接受初始化

udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_socket.bind(("", 7788))

#用于蜂鸣器的警报发声
def buzzer_sound(alerts):
    # 处理接收的数据,开启蜂鸣器警报
    buzzer = PWM(Pin(25))  #定义蜂鸣器管脚
    buzzer.duty(0) #初始化蜂鸣器
    
    if alerts == "1":
        #print("蜂鸣器响!!")
        buzzer.freq(3234)
        buzzer.duty(250)
        
    else:
        #print("蜂鸣器不响!!")
        buzzer.duty(0)
    

#用于调用各个模块
def buzzer_alert():
    while True:
        recv_data, sender_info = udp_socket.recvfrom(1024)
        #print("{}发送{}".format(sender_info, recv_data))
        recv_data_alerts = recv_data.decode("utf-8")
        if recv_data_alerts == '1':
            print(recv_data_alerts)
        buzzer_sound(recv_data_alerts)
    


if __name__ == "__main__":
    buzzer_alert()




